<template>
  <div class="container">
    <!-- <button class="floating-add-btn" @click="addNewItem">＋</button> -->
    <!-- 搜索框和筛选 -->
    <view class="search-filter-container">
      <view class="search-box">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input
          type="text"
          placeholder="请输入业主姓名"
          class="search-input"
          v-model="searchQuery"
          @input="getStationPage"
        />
        <uni-icons
          v-if="searchQuery"
          type="clear"
          size="16"
          color="#999"
          @click="
            searchQuery = '';
            getStationPage();
          "
        ></uni-icons>
      </view>

      <button class="filter-btn" @click="toggleFilterModal">
        <uni-icons type="filter" size="14" color="#666"></uni-icons>
        <text>筛选</text>
      </button>
    </view>

    <!-- 筛选模态框 -->
    <uni-popup ref="filterPopup" type="bottom" :mask-click="false">
      <view class="filter-modal">
        <view class="modal-header">
          <text class="modal-title">筛选条件</text>
          <uni-icons
            type="close"
            size="18"
            color="#999"
            @click="closeFilterModal"
          ></uni-icons>
        </view>

        <scroll-view scroll-y class="scrollable-content">
          <view class="filter-section">
            <text class="section-title">状态</text>
            <view class="status-buttons">
              <button
                v-for="(item, index) in statusOptions"
                :key="index"
                :class="{ active: filterStatus === item.value }"
                @click="filterStatus = item.value"
              >
                {{ item.label }}
              </button>
            </view>
          </view>

          <view class="filter-section">
            <text class="section-title">地区选择</text>
            <picker
              mode="multiSelector"
              @columnchange="handleColumnChange"
              :value="value"
              :range="range"
              @change="filterArea"
              class="area-picker"
            >
              <view class="picker-value">
                {{ selectedAreaText || "请选择省市区" }}
              </view>
            </picker>
          </view>
        </scroll-view>

        <view class="modal-footer">
          <button class="footer-btn reset" @click="resetFilters">重置</button>
          <button class="footer-btn confirm" @click="getStationPage">
            确认
          </button>
        </view>
      </view>
    </uni-popup>

    <!-- 电站列表 -->
    <scroll-view
      scroll-y
      class="station-list"
      :style="{ height: scrollViewHeight + 'px' }"
    >
      <view
        v-for="(owner, index) in owners"
        :key="index"
        class="station-card"
        @click="navigateToDetail(owner.id)"
      >
        <view class="card-header">
          <view class="station-info">
            <text class="station-name">{{ owner.guestname }}</text>
            <text class="station-no">{{ owner.stationno }}</text>
          </view>
          <!-- 修复：使用对象语法替代方法调用 -->
          <view
            class="status-badge"
            :class="{
              'status-online': owner.status === 1,
              'status-offline': owner.status === 0,
              'status-pending': owner.status === 2,
            }"
          >
            {{ getStatusText(owner.status) }}
          </view>
        </view>

        <view class="card-content">
          <view class="info-row">
            <uni-icons type="location" size="14" color="#666"></uni-icons>
            <text class="info-text">{{ owner.addressstring }}</text>
          </view>
          <view class="info-row">
            <uni-icons type="calendar" size="14" color="#666"></uni-icons>
            <text class="info-text">{{ formatDate(owner.createTime) }}</text>
          </view>
        </view>

        <view class="card-actions">
		<button class="action-btn" @click.stop="navigateToUpdate(owner.id)">
		  <uni-icons type="location" size="12" color="#666"></uni-icons>
		  <text>定位</text>
		</button>
          <button class="action-btn" @click.stop="handleCall(owner.phone)">
            <uni-icons type="phone" size="12" color="#666"></uni-icons>
            <text>拨打</text>
          </button>
          <button
            class="action-btn"
            @click.stop="fetchStationCoordinates(owner.id)"
          >
            <uni-icons type="map-pin" size="12" color="#666"></uni-icons>
            <text>导航</text>
          </button>
        </view>
      </view>

      <view v-if="owners.length === 0" class="empty-state">
        <uni-icons type="search" size="40" color="#ccc"></uni-icons>
        <text class="empty-text">暂无电站数据</text>
      </view>
    </scroll-view>
  </div>
</template>

<script>
import request from "@/utils/request.js";
import { getAccessToken } from "@/utils/auth";
import { tansParams } from "@/utils/common";
import * as StationApi from "@/api/oper/station/station.js";

export default {
  data() {
    const token = getAccessToken();
    // const params = {
    // 	pageNo: 1,
    // 	pageSize: 10,
    // };

    return {
      // params : params,
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        status: "",
        provinceId: "",
        cityId: "",
        areaId: "",
        addressstring: "",
      },
      token,
      searchQuery: "",
      owners: [],
      scrollViewHeight: 0,
      // 筛选相关
      filterStatus: "",
      statusOptions: [
        { label: "全部", value: "" },
        { label: "未定位", value: "0" },
        { label: "在线", value: "1" },
        { label: "离线", value: "2" },
        { label: "告警", value: "3" },
      ],
      provinces: [],
      cities: {},
      areas: {},
      range: [[], [], []], // picker 的多列数据
      value: [0, 0, 0],
      selectedValue: [],
      selectedAreaText: "",
    };
  },
  methods: {
    async getStationPage() {
      if (this.filterStatus) this.queryParams.status = this.filterStatus;

      if (this.selectedValue.length > 0) {
        this.queryParams.provinceId = this.provinces[this.selectedValue[0]].id;
        this.queryParams.cityId =
          this.cities[this.queryParams.provinceId][this.selectedValue[1]].id;
        this.queryParams.areaId =
          this.areas[this.queryParams.cityId][this.selectedValue[2]].id;
      }
      if (this.searchQuery) {
        this.queryParams.guestname = this.searchQuery;
      }
      console.log(this.queryParams);

      StationApi.getStationPage(this.queryParams).then((response) => {
        this.owners = response.data.list || [];

        if (this.searchQuery) {
          const keywords = this.searchQuery
            .split(/\s+/)
            .map((keyword) => keyword.toLowerCase());
          this.owners = this.owners.filter((owner) => {
            return keywords.some(
              (keyword) =>
                owner.guestname.toLowerCase().includes(keyword) ||
                owner.stationno.toLowerCase().includes(keyword) ||
                owner.addressstring.toLowerCase().includes(keyword)
            );
          });
        }
      });
    },

    toggleFilterModal() {
      this.$refs.filterPopup.open();
    },

    closeFilterModal() {
      this.$refs.filterPopup.close();
    },

    resetFilters() {
      console.log(this.params);
      this.queryParams = {
        pageNo: 1,
        pageSize: 10,
        status: "",
        provinceId: "",
        cityId: "",
        areaId: "",
        addressstring: "",
      };
      this.filterStatus = "";
      this.searchQuery = "";
      this.selectedValue = [];
      this.selectedAreaText = "";
      this.value = [0, 0, 0];
      this.getStationPage();
      this.closeFilterModal();
    },

    navigateToDetail(stationId) {
      uni.navigateTo({ url: `/pages/work/station/detail?id=${stationId}` });
    },
	
	navigateToUpdate(stationId) {
	  uni.navigateTo({ url: `/pages/work/station/update?id=${stationId}` });
	},

    getStatusText(status) {
      return status === 0 ? "未定位" : "已定位";
    },

    formatDate(timestamp) {
      if (!timestamp) return "";
      const date = new Date(timestamp);
      return `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
    },

    handleCall(phone) {
      if (!phone) {
        uni.showToast({
          title: "无联系电话",
          icon: "none",
        });
        return;
      }

      const platform = uni.getSystemInfoSync().platform;
      if (platform === "android" || platform === "ios") {
        uni.makePhoneCall({
          phoneNumber: phone,
          fail: (err) => {
            console.error("拨打电话失败:", err);
            uni.showToast({
              title: "拨号失败",
              icon: "none",
            });
          },
        });
      } else {
        window.location.href = `tel:${phone}`;
      }
    },

    async fetchStationCoordinates(stationId) {
      try {
        const response = await request({
          url: `/oper/station/get?id=${stationId}`,
          method: "GET",
          headers: { Authorization: `Bearer ${this.token}` },
        });

        const { latitude, longitude } = response.data || [];

        if (latitude && longitude) {
          const platform = uni.getSystemInfoSync().platform;

          if (platform === "android" || platform === "ios") {
            uni.openLocation({
              latitude: Number(latitude),
              longitude: Number(longitude),
              name: "电站位置",
              address: "请使用地图查看详细位置",
              scale: 18,
              fail: (err) => {
                console.error("打开地图失败:", err);
                uni.showToast({
                  title: "打开地图失败",
                  icon: "none",
                });
              },
            });
          } else {
            const amapUrl = `https://uri.amap.com/marker?position=${longitude},${latitude}`;
            window.open(amapUrl, "_blank");
          }
        } else {
          uni.showToast({
            title: "未获取到位置信息",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("获取电站经纬度失败:", error);
        uni.showToast({
          title: "获取位置失败",
          icon: "none",
        });
      }
    },

    addNewItem() {
      uni.navigateTo({ url: "/pages/work/station/create" });
    },

    async fetchAreas() {
      try {
        const response = await request({
          url: "/system/area/tree",
          method: "GET",
          headers: { Authorization: `Bearer ${this.token}` },
        });

        const areaData = response.data;
        this.provinces = areaData.map((province) => ({
          id: province.id,
          name: province.name,
        }));

        this.cities = {};
        this.areas = {};

        areaData.forEach((province) => {
          this.cities[province.id] = province.children.map((city) => ({
            id: city.id,
            name: city.name,
          }));

          province.children.forEach((city) => {
            this.areas[city.id] = city.children.map((area) => ({
              id: area.id,
              name: area.name,
            }));
          });
        });

        this.range[0] = this.provinces.map((p) => p.name);
        this.range[1] = this.cities[this.provinces[0].id].map((c) => c.name);
        this.range[2] = this.areas[this.cities[this.provinces[0].id][0].id].map(
          (a) => a.name
        );
      } catch (error) {
        console.error("获取地区数据失败:", error);
      }
    },

    filterArea(e) {
      const values = e.detail.value || this.value;
      this.selectedValue = values;

      const province = this.provinces[values[0]]?.name || "";
      const city =
        this.cities[this.provinces[values[0]]?.id][values[1]]?.name || "";
      const area =
        this.areas[this.cities[this.provinces[values[0]]?.id][values[1]]?.id][
          values[2]
        ]?.name || "";

      this.selectedAreaText = `${province} ${city} ${area}`;
    },

    handleColumnChange(event) {
      const { column, value } = event.detail;

      if (column === 0) {
        const selectedProvinceId = this.provinces[value].id;
        this.range[1] = this.cities[selectedProvinceId].map(
          (city) => city.name
        );
        this.range[2] =
          this.cities[selectedProvinceId].length > 0
            ? this.areas[this.cities[selectedProvinceId][0].id].map(
                (area) => area.name
              )
            : [];
        this.value[1] = 0;
        this.value[2] = 0;
      } else if (column === 1) {
        const selectedCityId =
          this.cities[this.provinces[this.value[0]].id][value].id;
        this.range[2] = this.areas[selectedCityId].map((area) => area.name);
        this.value[2] = 0;
      }

      this.value[column] = value;
      this.$forceUpdate();
    },

    async fetchAllOwners() {
      try {
        const response = await request({
          url: "/oper/station/page?pageSize=100",
          method: "GET",
          headers: { Authorization: `Bearer ${this.token}` },
        });
        this.owners = response.data.list || [];
      } catch (error) {
        console.error("获取所有电站数据失败", error);
        uni.showToast({
          title: "获取数据失败",
          icon: "none",
        });
      }
    },

    calculateScrollViewHeight() {
      const query = uni.createSelectorQuery().in(this);
      query
        .select(".container")
        .boundingClientRect((data) => {
          const systemInfo = uni.getSystemInfoSync();
          const windowHeight = systemInfo.windowHeight;
          const containerTop = data.top;
          this.scrollViewHeight = windowHeight - containerTop - 10;
        })
        .exec();
    },
  },

  mounted() {
    this.fetchAreas();
    this.getStationPage();
    // this.fetchAllOwners();
    this.calculateScrollViewHeight();

    uni.onWindowResize(() => {
      this.calculateScrollViewHeight();
    });
  },

  onBackPress() {
    if (this.$refs.filterPopup && this.$refs.filterPopup.isShow) {
      this.closeFilterModal();
      return true;
    }
    return false;
  },
};
</script>

<style lang="scss" scoped>
/* 新配色方案 */
$primary-color: #5a7dff; // 柔和的蓝色
$secondary-color: #6c757d; // 中性灰色
$light-bg: #f8f9fa; // 浅灰背景
$border-color: #dee2e6; // 边框颜色
$text-color: #333;
$text-secondary: #666;
$text-light: #999;
$bg-color: #f5f7fa;

.container {
  padding: 12px;
  background-color: $bg-color;
  min-height: 100vh;
  box-sizing: border-box;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  .title {
    font-size: 20px;
    font-weight: 600;
    color: $text-color;
  }

  .header-actions {
    width: 36px;
    height: 36px;
    background-color: $primary-color;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: 0 2px 6px rgba($primary-color, 0.1);
  }
}

.search-filter-container {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  gap: 8px;

  .search-box {
    flex: 1;
    display: flex;
    align-items: center;
    background-color: #fff;
    padding: 6px 12px;
    border-radius: 18px;
    height: 36px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

    .search-input {
      flex: 1;
      margin: 0 8px;
      font-size: 14px;
      color: $text-color;
      height: 100%;
    }

    uni-icons {
      flex-shrink: 0;
    }
  }

  .filter-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 12px;
    height: 36px;
    background-color: #fff;
    color: $secondary-color;
    border: 1px solid $border-color;
    border-radius: 18px;
    font-size: 12px;

    uni-icons {
      margin-right: 4px;
    }

    &:active {
      background-color: $light-bg;
    }
  }
}

.filter-modal {
  background-color: #fff;
  border-radius: 16px 16px 0 0;
  padding-bottom: env(safe-area-inset-bottom);

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid $border-color;

    .modal-title {
      font-size: 16px;
      font-weight: 600;
      color: $text-color;
    }
  }

  .scrollable-content {
    max-height: 50vh;
    padding: 12px 16px;
  }

  .filter-section {
    margin-bottom: 16px;

    .section-title {
      display: block;
      font-size: 14px;
      color: $text-color;
      margin-bottom: 8px;
      font-weight: 500;
    }

    .status-buttons {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      button {
        flex: 1;
        min-width: 30px;
        background-color: #fff;
        color: $secondary-color;
        border: 1px solid $border-color;
        border-radius: 16px;
        padding: 2px 0;
        font-size: 12px;
        height: 32px;

        &.active {
          background-color: rgba($primary-color, 0.1);
          color: $primary-color;
          border-color: $primary-color;
        }
      }
    }

    .area-picker {
      .picker-value {
        padding: 10px 12px;
        background-color: #f5f7fa;
        border-radius: 6px;
        color: $text-color;
        font-size: 13px;
      }
    }
  }

  .modal-footer {
    display: flex;
    padding: 12px 16px;
    border-top: 1px solid $border-color;
    gap: 12px;

    .footer-btn {
      flex: 1;
      padding: 3px 0;
      height: 40px;
      border-radius: 6px;
      font-size: 14px;
      font-weight: 500;

      &.reset {
        background-color: #fff;
        color: $secondary-color;
        border: 1px solid $border-color;
      }

      &.confirm {
        background-color: $primary-color;
        color: #fff;
        border: 1px solid $primary-color;
      }

      &:active {
        opacity: 0.8;
      }
    }
  }
}

.station-list {
  .station-card {
    background-color: #fff;
    border-radius: 10px;
    padding: 12px;
    margin-bottom: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;

      .station-info {
        flex: 1;
        .station-name {
          font-size: 15px;
          font-weight: 600;
          color: $text-color;
          margin-right: 8px;
        }

        .station-no {
          font-size: 11px;
          color: $text-light;
          background-color: #f5f5f5;
          padding: 2px 6px;
          border-radius: 3px;
        }
      }

      .status-badge {
        font-size: 11px;
        padding: 3px 8px;
        border-radius: 10px;
        color: #fff;

        &.status-online {
          background-color: #28a745; // 柔和的绿色
        }

        &.status-offline {
          background-color: #dc3545; // 柔和的红色
        }

        &.status-pending {
          background-color: #ffc107; // 柔和的黄色
        }
      }
    }

    .card-content {
      .info-row {
        display: flex;
        align-items: center;
        margin-bottom: 6px;

        uni-icons {
          flex-shrink: 0;
        }

        .info-text {
          margin-left: 6px;
          font-size: 13px;
          color: $text-secondary;
          line-height: 1.4;
        }
      }
    }

    .card-actions {
      display: flex;
      margin-top: 12px;

      .action-btn {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 5px 0;
        height: 28px;
        background-color: #fff;
        color: $secondary-color;
        border: 1px solid $border-color;
        border-radius: 16px;
        font-size: 12px;

        uni-icons {
          margin-right: 4px;
        }

        &:first-child {
          margin-right: 8px;
        }

        &:active {
          background-color: $light-bg;
        }
      }
    }
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 30px 0;

    .empty-text {
      margin-top: 12px;
      color: $text-light;
      font-size: 13px;
    }
  }
}
/* 修复：将浮动按钮样式移到最外层 */
.floating-add-btn {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #007bff;
  color: white;
  font-size: 24px;
  font-weight: bold;
  border: none;
  cursor: pointer;
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2);
  display: flex;
  justify-content: center;
  align-items: center;
  transition: background-color 0.3s;
  z-index: 999; /* 添加z-index确保按钮在最上层 */
}

.floating-add-btn:hover {
  background-color: #0056b3;
}
</style>
